<template>
  <div class="order-list">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>订单管理</h2>
      <el-button type="primary" @click="handleShowCreateModal" :icon="Plus">
        新建订单
      </el-button>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <div class="search-filter">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索订单号或客户姓名"
        prefix-icon="el-icon-search"
        clearable
        style="width: 300px; margin-right: 10px;"
        @keyup.enter="handleSearch"
      />
      
      <el-select
        v-model="status"
        placeholder="订单状态"
        clearable
        style="width: 150px; margin-right: 10px;"
        @change="handleStatusChange"
      >
        <el-option label="待打印" value="pending"></el-option>
        <el-option label="已打印" value="printed"></el-option>
      </el-select>
      
      <el-button type="primary" @click="handleSearch" :icon="Search">
        搜索
      </el-button>
      
      <el-button @click="handleReset" :icon="Refresh">
        重置
      </el-button>
    </div>
    
    <!-- 订单列表 -->
    <div class="order-table">
      <el-table
        :data="orders"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        :row-key="(row) => row.id"
      >
        <el-table-column prop="order_no" label="订单号" width="200"></el-table-column>
        <el-table-column prop="customer_name" label="客户姓名" width="150"></el-table-column>
        <el-table-column prop="customer_phone" label="客户电话" width="150"></el-table-column>
        <el-table-column prop="items" label="商品明细" width="200">
          <template #default="scope">
            <el-popover
              placement="top"
              trigger="hover"
              :width="500"
              popper-class="item-detail-popover"
            >
              <template #reference>
                <span class="item-summary">{{ scope.row.items ? scope.row.items.length : 0 }} 种商品</span>
              </template>
              <div v-if="scope.row.items && scope.row.items.length > 0" class="item-detail">
                <div class="item-header">
                  <span class="header-name">商品名</span>
                  <span class="header-qty">数量</span>
                  <span class="header-price">单价</span>
                  <span class="header-total">总价</span>
                </div>
                <div v-for="(item, index) in scope.row.items" :key="index" class="item-row">
                  <span class="item-name">{{ item.name }}</span>
                  <span class="item-qty">{{ item.quantity || 0 }}</span>
                  <span class="item-price">¥{{ item.price || 0 }}</span>
                  <span class="item-total">¥{{ (item.price && item.quantity) ? (item.price * item.quantity).toFixed(2) : 0 }}</span>
                </div>
              </div>
              <div v-else class="no-items">无商品信息</div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="print_status" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="formatOrderStatus(scope.row.print_status).type">
              {{ formatOrderStatus(scope.row.print_status).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="order_time" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.order_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              text
              @click="handleShowPrintPreview(scope.row.id)"
              :disabled="scope.row.print_status === 1"
              :loading="printingIds.includes(scope.row.id)"
            >
              {{ scope.row.print_status === 1 ? '已打印' : '打印预览' }}
            </el-button>
            <el-button
              type="warning"
              text
              @click="handleEditOrder(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              text
              @click="handleDeleteConfirm(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handlePageSizeChange"
        @current-change="handlePageChange"
      />
    </div>
    
    <!-- 确认删除对话框 -->
    <el-dialog
      v-model="deleteConfirmVisible"
      title="确认删除"
      width="30%"
      @close="handleCancelDelete"
    >
      <span>确定要删除订单 {{ selectedOrder?.id }} 吗？</span>
      <template #footer>
        <el-button @click="handleCancelDelete">取消</el-button>
        <el-button type="danger" @click="handleConfirmDelete" :loading="deleting">
          确定删除
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 创建订单对话框 -->
    <CreateOrderModal
      v-model="showCreateModal"
      @success="handleOrderCreated"
    />
    
    <!-- 编辑订单对话框 -->
    <EditOrderModal
      v-model="showEditModal"
      :order-id="selectedOrder?.id"
      @success="handleOrderUpdated"
    />
    
    <!-- 打印预览对话框 -->
    <PrintPreviewModal
      v-model="showPrintPreviewModal"
      :order-id="previewOrderId"
      @print-success="handlePrintSuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, Search, Refresh, Printer, Delete, Edit } from '@element-plus/icons-vue';
import CreateOrderModal from '../components/CreateOrderModal.vue';
import EditOrderModal from '../components/EditOrderModal.vue';
import PrintPreviewModal from '../components/PrintPreviewModal.vue';
import { useOrders } from '../hooks/useOrders';

// 使用订单相关的hook
const {
  orders,
  loading,
  currentPage,
  pageSize,
  total,
  searchKeyword,
  status,
  loadOrders,
  handleSearch,
  handlePageChange,
  handlePageSizeChange,
  handlePrintOrder,
  handleUpdateOrder,
  handleDeleteOrder,
  formatDate,
  formatOrderStatus
} = useOrders();
// 对话框相关
const showCreateModal = ref(false);
const showEditModal = ref(false);
const showPrintPreviewModal = ref(false);
const selectedOrder = ref(null);
const previewOrderId = ref(null);
const deleteConfirmVisible = ref(false);// 操作状态
const printingIds = ref([]);
const deleting = ref(false);

// 初始加载数据
onMounted(() => {
  loadOrders();
});

// 显示创建订单对话框
const handleShowCreateModal = () => {
  showCreateModal.value = true;
};

// 处理订单创建成功
const handleOrderCreated = () => {
  loadOrders(); // 重新加载订单列表
};

// 处理订单编辑
const handleEditOrder = (order) => {
  selectedOrder.value = { ...order };
  showEditModal.value = true;
};

// 处理订单编辑成功
const handleOrderUpdated = () => {
  loadOrders(); // 重新加载订单列表
};

// 处理删除确认
const handleDeleteConfirm = (order) => {
  selectedOrder.value = { ...order };
  deleteConfirmVisible.value = true;
};

// 取消删除
const handleCancelDelete = () => {
  deleteConfirmVisible.value = false;
  selectedOrder.value = null;
};

// 确认删除
const handleConfirmDelete = async () => {
  if (!selectedOrder.value?.id) return;
  
  deleting.value = true;
  try {
    const success = await handleDeleteOrder(selectedOrder.value.id);
    if (success) {
      deleteConfirmVisible.value = false;
      selectedOrder.value = null;
    }
  } finally {
    deleting.value = false;
  }
};

// 重置筛选条件
const handleReset = () => {
  searchKeyword.value = '';
  status.value = '';
  currentPage.value = 1;
  loadOrders();
};

// 处理状态筛选变化
const handleStatusChange = () => {
  currentPage.value = 1;
  loadOrders();
};

// 显示打印预览
const handleShowPrintPreview = (orderId) => {
  previewOrderId.value = orderId;
  showPrintPreviewModal.value = true;
};

// 处理打印成功
const handlePrintSuccess = (orderId) => {
  loadOrders(); // 重新加载订单列表
};
</script>

<style scoped>
.order-list {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-filter {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.order-table {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

/* 商品明细样式 */
.item-summary {
  color: #409EFF;
  cursor: pointer;
}

.item-summary:hover {
  text-decoration: underline;
}

.item-detail {
  max-height: 300px;
  overflow-y: auto;
}

.item-header {
  display: flex;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-bottom: 2px solid #e4e7ed;
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.item-row {
  display: flex;
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
}

.item-row:last-child {
  border-bottom: none;
}

.item-name,
.header-name {
  flex: 2;
  min-width: 180px;
}

.item-name {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-qty,
.header-qty,
.item-price,
.header-price,
.item-total,
.header-total {
  flex: 1;
  text-align: center;
  font-size: 14px;
}

.header-qty,
.header-price,
.header-total {
  min-width: 60px;
}

.item-qty {
  color: #303133;
}

.item-price {
  color: #606266;
}

.item-total {
  color: #f56c6c;
  font-weight: 500;
}

.no-items {
  text-align: center;
  color: #909399;
  padding: 10px;
}

.item-detail-popover {
  font-size: 14px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .search-filter {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-filter .el-input {
    width: 100% !important;
    margin-right: 0 !important;
  }
  
  .search-filter .el-select {
    width: 100% !important;
    margin-right: 0 !important;
  }
}
</style>